﻿using Protocol.Code;
using Protocol.Dto;
using Script.Framework;
using Script.UI.Msg;
using UnityEngine;
using UnityEngine.UI;

namespace Script.UI._0.Login
{
    public class StartPanel : UIBase
    {
        private void Awake()
        {
            //Debug.Log("我他妈运行了");

            Bind(UIEvent.START_PANEL_ACTIVE);
        }

        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case UIEvent.START_PANEL_ACTIVE:
                    SetPanelActive((bool) message);
                    break;
            }
        }


        private Button btnLogin;
        private Button btnClose;
        private InputField inputAccount;
        private InputField inputPassword;


        private PromptMsg promptMsg;
        private SocketMsg socketMsg;


        private void Start()
        {
            // 获取对象
            btnLogin = transform.Find("Btn_Login").GetComponent<Button>();
            btnClose = transform.Find("Btn_Close").GetComponent<Button>();
            inputAccount = transform.Find("Account").GetComponent<InputField>();
            inputPassword = transform.Find("Password").GetComponent<InputField>();

            // 事件注册
            btnLogin.onClick.AddListener(LoginClick);
            btnClose.onClick.AddListener(CloseClick);

            // 创建对象
            promptMsg = new PromptMsg();
            socketMsg = new SocketMsg();

            SetPanelActive(false);
        }

        public override void OnDestroy()
        {
            base.OnDestroy();

            btnLogin.onClick.RemoveAllListeners();
            btnClose.onClick.RemoveAllListeners();
        }

        /// <summary>
        /// 登录按钮的点击事件处理
        /// </summary>
        private void LoginClick()
        {
            if (string.IsNullOrEmpty(inputAccount.text))
            {
                promptMsg.Change("登录账号不能为空", Color.red);
                Dispatch(AreaCode.UI, UIEvent.PROMPT_MSG, promptMsg);
                return;
            }

            if (string.IsNullOrEmpty(inputPassword.text) ||
                inputPassword.text.Length < 4 ||
                inputPassword.text.Length > 16)
            {
                promptMsg.Change("登录密码输入不合规范", Color.red);
                Dispatch(AreaCode.UI, UIEvent.PROMPT_MSG, promptMsg);
                return;
            }

            AccountDto dto = new AccountDto(inputAccount.text, inputPassword.text);
            socketMsg.Change(OpCode.ACCOUNT, AccountCode.LOGIN, dto);
            Dispatch(AreaCode.NET, 0, socketMsg);
        }


        private void CloseClick()
        {
            SetPanelActive(false);
        }
    }
}